package service

import (
	"comm/dto"
	"comm/qto"
	"core/corestruct"
	"core/datetime"
	"core/id"
	"core/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/bson/primitive"
)

type mainService struct {
}

// Page 设备分页
func (p *mainService) Page(mm *qto.CommConnectInfoQto, ctx *corestruct.HttpContext) (*corestruct.Page[dto.CommConnectInfoDto], error) {
	var filter = make(bson.M)
	if mm.Id > 0 {
		filter["_id"] = mm.Id
	} else {
		if "" != mm.Sid {
			filter["sid"] = mm.Sid
		}
		if mm.CommPortId > 0 {
			filter["CommPortId"] = mm.CommPortId
		}
		if mm.CommProxyId > 0 {
			filter["CommProxyId"] = mm.CommProxyId
		}
		if "" != mm.Key {
			filter["sid"] = bson.M{"$regex": primitive.Regex{
				Pattern: mm.Key,
				Options: "",
			}}
		}
	}
	var dtb, err = mm.GetDtb()
	if err != nil {
		return nil, err
	}
	dte, err := mm.GetDte()
	if err != nil {
		return nil, err
	}
	var pgsvr = &mongo.PageDtService[dto.CommConnectInfoDto]{
		ColBaseName: "CommConnectInfo",
		Filer:       filter,
		Dtb:         *dtb,
		Dte:         *dte,
		PageNo:      mm.Page,
		PageSize:    mm.PageSize,
	}

	r, err := pgsvr.Page()
	if err != nil {
		return nil, err
	}

	for index, v := range r.Records {
		var dt = id.GetDateById(v.Id)
		r.Records[index].CrtDt = datetime.FormatDateTime(dt)

	}
	return r, nil
}

var (
	MainService = &mainService{}
)
